package com.woyao;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.woyao.core.model.GetChildHowResponse;
import com.woyao.core.model.How;
import com.woyao.core.service.HowService;
import com.woyao.core.util.ServiceFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import retrofit2.Call;

public class ConfirmHow extends AppCompatActivity {
    TextView howtitle = null;
    HashMap<String,String> parents = new HashMap<String,String>() ;

    private  String curhow = "";

    LinearLayoutManager allLayoutManager = null;
    private RecyclerView alllist = null;
    private HowListAdapter allAdapter;

    Boolean changed = false;
    ProgressDialog progressDialog;
    String from = "";
    private boolean is_new = true;

    private String member_title="";
    private Integer member_id = 0;

    private Integer COMPLETE_DEMAND_CODE = 100;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_confirm_how);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(toolbar);
        final ActionBar ab = getSupportActionBar();
        //       ab.setHomeAsUpIndicator(R.drawable.icon_menu); // set a custom icon for the default home button
        ab.setDisplayShowHomeEnabled(true); // show or hide the default home button
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setDisplayShowCustomEnabled(true); // enable overriding the default toolbar layout
//        ab.setDisplayShowTitleEnabled(false); // disable the default title element


        alllist = (RecyclerView) findViewById(R.id.id_how_list);
        allLayoutManager = new LinearLayoutManager(this);
        allLayoutManager.setOrientation(OrientationHelper.VERTICAL);
        alllist.setLayoutManager(allLayoutManager);
        alllist.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));

        Button roottitle = (Button) findViewById(R.id.how_roottitle);

        roottitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                curhow ="";
                howtitle.setText(  curhow );
                loadAllData();
            }
        });

        howtitle = (TextView) findViewById(R.id.alltitle);

        Button gobackbtn = (Button) findViewById(R.id.goback);

        gobackbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (parents.get(curhow ) != null) {

                    curhow = parents.get(curhow ) ;
                    howtitle.setText(  "" );
                    loadAllData();
                }
            }
        });

        Intent intent = getIntent();
        from = intent.getStringExtra( "from");
        if (from == null){
            from = "";
        }

        is_new = intent.getBooleanExtra( "is_new", true);

        member_id = intent.getIntExtra( "member_id", 0);
        member_title = intent.getStringExtra( "member_title");
        if (member_title == null){
            member_title = "" ;
        }
//        KeyValueList how_list = (KeyValueList)intent.getExtras().get("how_list");

        this.setTitle("请说明合作需求");

        loadAllData();

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent intent = new Intent();
        intent.putExtra("changed", changed );
        setResult(0, intent);
        finish();

        return true;
    }




   private void loadAllData(){
        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("拼命加载中······");
        progressDialog.show();

        AsyncTask<Void,Void,GetChildHowResponse> task =
                new AsyncTask<Void, Void, GetChildHowResponse>() {
                    @Override
                    protected GetChildHowResponse doInBackground(Void... params) {
                        HowService svc = ServiceFactory.get(HowService.class);
                        Call<GetChildHowResponse> responseCall = svc.getChildHow(curhow,WoyaoooApplication.userId,"");
                        try {
                            GetChildHowResponse response = responseCall.execute().body();
                            return response;
                        } catch (IOException e) {
                            e.printStackTrace();
                            return null;
                        }
                    }
                    @Override
                    protected void onPostExecute(final GetChildHowResponse response) {
                        progressDialog.dismiss();
                        ArrayList<How> hows = response.getHowList();
                        renderAll(hows);
                    }
                    @Override
                    protected void onCancelled() {
                        progressDialog.dismiss();
                    }
                };
        task.execute();
    }


    private void renderAll( ArrayList<How> hows ){



        allAdapter = new HowListAdapter(this,  hows );



        allAdapter.setChangedHandler(new HowListAdapter.Changed() {
            @Override
            public void itemSelected(How one) {

                Intent intent = new Intent();
                intent.putExtra("is_new", true );
                intent.putExtra("result",one );
                intent.putExtra("member_id",member_id );
                intent.putExtra("member_title",member_title );
                intent.setClass(ConfirmHow.this, DemandNewActivity.class);
                startActivityForResult(intent, COMPLETE_DEMAND_CODE);
            }


            @Override
            public void itemGetChildren(How one) {

                parents.put(one.getNo(), curhow );
                curhow = one.getNo();
                howtitle.setText( one.getName() );

                loadAllData();
            }
        });


        this.alllist.setAdapter(allAdapter);



    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == 666 && requestCode == COMPLETE_DEMAND_CODE) {

            Intent intent = new Intent();
            Integer demand_id = data.getIntExtra("demand_id", 0);
            if (demand_id == 0) {
                intent.putExtra("demand_id", demand_id);
                intent.putExtra("changed", false);
                setResult(0, intent);
            } else {
                intent.putExtra("demand_id", demand_id);
                intent.putExtra("changed", true);
                setResult(666, intent);
            }
            finish();
        }

    }



        @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (curhow.length() == 2 ){
                curhow ="";
                howtitle.setText(  curhow );
                loadAllData();
                return true;
            }else {
                Intent intent = new Intent();
                intent.putExtra("changed", changed);
                setResult(0, intent);
                finish();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

}

